package com.luoran.bartalks.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.Tree;
import com.luoran.bartalks.entity.biz.BtPlanTemplate;
import com.luoran.bartalks.entity.biz.BtPosition;
import com.luoran.bartalks.entity.biz.BtRegion;
import com.luoran.bartalks.service.IBtCodingRuleService;
import com.luoran.bartalks.service.IBtPlanTemplateService;
import com.luoran.bartalks.service.IBtPositionService;
import com.luoran.bartalks.service.IBtRegionService;
import com.luoran.bartalks.utils.EnumBillType;

@Controller
@RequestMapping("/position")
public class BtPositionAction implements Pageable {

	@Autowired
	private IBtPositionService service;

	@Autowired
	private IBtRegionService iBtRegionService;

	@Autowired
	private IBtCodingRuleService codingRuleService;

	@Autowired
	private IBtPlanTemplateService planTemplateService;

	private static final Logger log = LoggerFactory.getLogger(BtPositionAction.class);

	
	
	/**
	 * 区域管理列表页面
	 * 
	 * @return
	 */
	@RequestMapping
	public String queryPosition() {
		log.info("跳转到>>区域位置管理列表页面");
		return "basics/position-list";
		// return "basics/position-list2";
	}
	
	
	@RequestMapping("/tree")
	@ResponseBody
	public JSONObject tree() {
		JSONObject obj = new JSONObject();
		// query
		List<BtRegion> btRegions = iBtRegionService.getRegionByCompanyId(UserContext.get().getCompanyId());
		List<BtPosition> btRegPositionist = service.getPositionByCompanyId(UserContext.get().getCompanyId());
		List<Tree> treeList = new ArrayList<Tree>();
		if (btRegions.size() > 0 && !btRegions.isEmpty()) {
			for (int i = 0; i < btRegions.size(); i++) {
				Tree tree = new Tree();
				tree.setId(btRegions.get(i).getRegionCode());
				if (!StringUtils.isEmpty(btRegions.get(i).getParentRegCode())) {
					tree.setpId(btRegions.get(i).getParentRegCode());
				} else {
					tree.setpId("0");
				}
				tree.setName(btRegions.get(i).getRegionName());
				tree.setIsParent("true");
				treeList.add(tree);
			}
		}

		if (btRegPositionist.size() > 0 && !btRegPositionist.isEmpty()) {
			for (int i = 0; i < btRegPositionist.size(); i++) {
				Tree tree = new Tree();
				tree.setId(btRegPositionist.get(i).getPositionCode());
				tree.setpId(btRegPositionist.get(i).getParentRegPositionCode());
				tree.setName(btRegPositionist.get(i).getPositionName());
				tree.setIsParent("false");
				treeList.add(tree);
			}
		}
		obj.put("data", treeList);
		return obj;
	}

	/**
	 * 位置管理列表数据
	 * 
	 * @return
	 */
	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		log.info("获取位置管理列表数据,page:" + pageQuery.getPageNumber() + "size:" + pageQuery.getPageSize());
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) pageQuery.getParas();
		map.put("companyId", UserContext.get().getCompanyId());// 添加查询参数（公司ID）
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("create_time DESC");
		}
		return service.getQueryList(pageQuery);
	}

	// 生成编码
	@RequestMapping("/generateCode")
	@ResponseBody
	public JSONObject gennerateCompanyCoding() {
		return codingRuleService.generateCoding(EnumBillType.POSITION, UserContext.get().getCompanyId());
	}

	

	@RequestMapping("addPosit")
	@ResponseBody
	public JSONObject addPosition(BtPosition position) {
		log.info("新增位置信息》》");
		JSONObject res = new JSONObject();
		res = check(position);
		if (!res.getBooleanValue("state")) {
			return res;
		}
		if (StringUtils.isEmpty(position.getPositionCode())) {
			res.put("msg", "位置编码不可以为空！");
			res.put("state", false);
			return res;
		} else if (position.getPositionCode().length() > 100) {
			res.put("msg", "编码长度限制为100！");
			res.put("state", false);
			return res;
		}
		if (StringUtils.isEmpty(position.getParentRegPositionCode())) {
			res.put("msg", "区域编码不可以为空！");
			res.put("state", false);
			return res;
		} else if (position.getParentRegPositionCode().length() > 100) {
			res.put("msg", "区域编码长度限制为100！");
			res.put("state", false);
			return res;
		}
		// 搜索是否已经存在
		BtPosition positionInfo = service.getPositByPositionCode(position.getPositionCode(),
				UserContext.get().getCompanyId());
		if (positionInfo == null) {
			position.setCreateTime(new Date());
			position.setFounder(UserContext.get().getCompanyId());
			position.setCompanyId(UserContext.get().getCompanyId());
			position.setState(0);
			position = service.addPosit(position);
			res.put("msg", "新增成功！");
			res.put("state", true);
			return res;
		} else {
			res.put("msg", "位置编码“" + position.getPositionCode() + "”已被其他引用！");
			res.put("state", true);
			return res;
		}
	}

	private JSONObject check(BtPosition position) {
		JSONObject res = new JSONObject();
		if (StringUtils.isEmpty(position.getPositionName())) {
			res.put("msg", "位置名称不可以为空！");
			res.put("state", false);
			return res;
		} else if (position.getPositionName().length() > 100) {
			res.put("msg", "名称长度限制为100！");
			res.put("state", false);
			return res;
		} else if (StringUtils.isEmpty(position.getLongitude()) || StringUtils.isEmpty(position.getLatitude())) {
			res.put("msg", "经纬度不能为空! 请点击地图获取!");
			res.put("state", false);
			return res;
		} else if (position.getPositionDesc().length() > 500) {
			res.put("msg", "描述长度限制为500！");
			res.put("state", false);
			return res;
		}
		res.put("state", true);
		return res;
	}

	@RequestMapping("editPosit")
	@ResponseBody
	public JSONObject editPosition(BtPosition position) {
		log.info("编辑位置信息》》");
		JSONObject res = new JSONObject();
		res = check(position);
		if (!res.getBooleanValue("state")) {
			return res;
		} else {
			service.editPosition(position);
			res.put("msg", "修改成功！");
			res.put("state", true);
			return res;
		}
	}

	@RequestMapping("/checkPosit/{id}")
	@ResponseBody
	public JSONObject checkPosit(@PathVariable("id") String id) {
		JSONObject res = new JSONObject();
		List<BtPlanTemplate> btPlanTemplates = planTemplateService
				.getBtPlanTemplateByCompanyId(UserContext.get().getCompanyId());
		BtPosition btRegPosition = service.getPositionById(id);
		for (BtPlanTemplate btPlanTemplate : btPlanTemplates) {
			if ((btPlanTemplate.getDestinationCode()).equals(btRegPosition.getPositionName())
					|| (btPlanTemplate.getStartPlaceCode()).equals(btRegPosition.getPositionName())) {
				res.put("state", true);
			}
		}
		return res;
	}

	@RequestMapping("/deletePosit/{id}")
	@ResponseBody
	public JSONObject deletePosit(@PathVariable("id") String id) {
		JSONObject res = new JSONObject();
		log.info("删除位置信息》》");
		BtPosition position = new BtPosition();
		position.setId(id);
		position.setState(1);
		service.editPosition(position);
		res.put("msg", "删除成功！");
		res.put("state", true);
		return res;
	}

	@GetMapping("/getPosit/{id}")
	@ResponseBody
	public JSONObject getPosit(@PathVariable("id") String id) {
		log.info("根据位置 Id 获取位置信息》》");
		JSONObject res = new JSONObject();
		BtPosition position = service.getPositionById(id);
		res.put("obj", position);
		res.put("state", true);
		return res;
	}
}
